import asyncio
import streamlit as st
import sys
from MCPClient import MCPClient

def setup_streamlit():
    st.set_page_config(page_title="MCP 客户端控制台", layout="wide")
    st.title("🎮 MCP 客户端交互控制台")
    
    if 'client' not in st.session_state:
        st.session_state.client = None
        st.session_state.connected = False

async def connect_server_async(server_path):
    try:
        client = MCPClient()
        await client.connect_to_server(server_path)
        return client, None
    except Exception as e:
        return None, str(e)

asyncio.run(connect_server_async("horoscopeServer.py"))

def main():
    setup_streamlit()
    
    with st.sidebar:
        st.header("服务器配置")
        server_path = st.text_input("🖥️ 服务器脚本路径", help="输入要连接的MCP服务器脚本路径（.py或.js）")
        
        if st.button("🔗 连接服务器", use_container_width=True):
            if not server_path:
                st.error("⚠ 请输入有效的服务器脚本路径")
            else:
                with st.spinner("正在建立服务器连接..."):
                    loop = asyncio.new_event_loop()
                    asyncio.set_event_loop(loop)
                    client, error = loop.run_until_complete(connect_server_async(server_path))
                    if client:
                        st.session_state.client = client
                        st.session_state.connected = True
                        st.success("✅ 服务器连接成功！")
                    else:
                        st.error(f"连接失败: {error}")

    if st.session_state.connected:
        st.subheader("💬 客户端交互")
        user_input = st.text_input("输入你的消息（输入'quit'退出）", key="user_input")
        
        if user_input:
            if user_input.lower() == 'quit':
                st.session_state.connected = False
                st.session_state.client = None
                st.rerun()
            else:
                async def process_query_async():
                    try:
                        response = await st.session_state.client.process_query(user_input)
                        st.session_state.response = response
                    except Exception as e:
                        st.error(f"处理请求时出错: {str(e)}")
                
                with st.spinner("DeepSeek正在思考..."):
                    loop = asyncio.new_event_loop()
                    asyncio.set_event_loop(loop)
                    loop.run_until_complete(process_query_async())
                    
                if 'response' in st.session_state:
                    st.markdown(f"""
                    <div style="padding:15px; background:#f0f2f6; border-radius:10px; margin-top:10px">
                        <strong>🤖 DeepSeek回复:</strong><br/>
                        {st.session_state.response}
                    </div>
                    """, unsafe_allow_html=True)

if __name__ == "__main__":
    main()
